package com.dmcloud.common.base;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmcloud.common.constant.DmConstants;
import com.dmcloud.common.util.auth.AuthUtils;
import com.dmcloud.common.util.auth.DmUser;

import java.time.LocalDateTime;
import java.util.Collection;

/**
 * Created by xiaodao
 * date: 2020/5/18
 * 基类封装 自动加入 createBy 和 updateBy
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity>  extends ServiceImpl<M,T> implements BaseService<T> {
    @Override
    public boolean save(T entity) {
        this.resolveEntity(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(T entity) {
        this.resolveEntity(entity);
        return super.updateById(entity);
    }

    @Override
    public boolean saveBatch(Collection<T> entityList, int batchSize) {
        entityList.forEach(this::resolveEntity);
        return super.saveBatch(entityList, batchSize);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
        entityList.forEach(this::resolveEntity);
        return super.saveOrUpdateBatch(entityList, batchSize);
    }

    @Override
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        entityList.forEach(this::resolveEntity);
        return super.updateBatchById(entityList, batchSize);
    }

    @Override
    public boolean saveOrUpdate(T entity) {
        if (entity.getId() == null) {
            return this.save(entity);
        } else {
            return this.updateById(entity);
        }
    }

    private void resolveEntity(T entity){
        DmUser user = AuthUtils.getUser();
        if(entity.getId() == null){
            //处理新增逻辑
            if(user !=null){
                entity.setCreateBy(user.getId());
                entity.setUpdateBy(user.getId());
            }
            entity.setCreateTime(LocalDateTime.now());
        }else if(user !=null){
            //处理修改逻辑
            entity.setUpdateBy(user.getId());
        }
        //通用处理
        entity.setUpdateTime(LocalDateTime.now());
        entity.setDelFlag(DmConstants.NOT_DELETED);

    }

}
